package com.common.utils;

import android.content.Context;
import android.os.Environment;

import com.common.R;

import java.io.File;

public class FilePathManager {
    private static FilePathManager instance;
    private Context context;

    // 应用内部存储目录
    private File internalFilesDir;
    private File internalCacheDir;

    // 应用外部存储私有目录
    private File externalFilesDir;
    private File externalCacheDir;

    // 公共下载目录中的应用专属目录
    private File publicDownloadDir;

    private FilePathManager(Context context) {
        this.context = context.getApplicationContext();
        initDirs();
    }

    public static synchronized FilePathManager getInstance(Context context) {
        if (instance == null) {
            instance = new FilePathManager(context);
        }
        return instance;
    }

    private void initDirs() {
        // 初始化内部存储目录
        internalFilesDir = context.getFilesDir();
        internalCacheDir = context.getCacheDir();

        // 初始化外部存储私有目录
        if (isExternalStorageAvailable()) {
            externalFilesDir = context.getExternalFilesDir(null);
            externalCacheDir = context.getExternalCacheDir();
        }

        // 初始化公共下载目录中的应用专属目录
        if (isExternalStorageAvailable()) {
            publicDownloadDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                    context.getString(R.string.downPath)
            );

            // 创建目录（如果不存在）
            if (!publicDownloadDir.exists()) {
                publicDownloadDir.mkdirs();
            }
        }
    }

    // 检查外部存储是否可用
    private boolean isExternalStorageAvailable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    // 获取内部文件目录
    public File getInternalFilesDir() {
        return internalFilesDir;
    }

    // 获取内部缓存目录
    public File getInternalCacheDir() {
        return internalCacheDir;
    }

    // 获取外部文件目录
    public File getExternalFilesDir() {
        return externalFilesDir;
    }

    // 获取外部缓存目录
    public File getExternalCacheDir() {
        return externalCacheDir;
    }

    // 获取公共下载目录中的应用专属目录
    public File getPublicDownloadDir() {
        return publicDownloadDir;
    }

    // 在内部文件目录中创建文件
    public File createFileInInternalDir(String fileName) {
        return new File(internalFilesDir, fileName);
    }

    // 在外部文件目录中创建文件
    public File createFileInExternalDir(String fileName) {
        if (externalFilesDir == null) return null;
        return new File(externalFilesDir, fileName);
    }

    // 在公共下载目录中创建文件
    public File createFileInPublicDownloadDir(String fileName) {
        if (publicDownloadDir == null) return null;
        return new File(publicDownloadDir, fileName);
    }
}
